import { useEffect, useState } from 'react';
import { message } from 'antd';
import { CheckOutlined, CloseOutlined, RightOutlined, LoadingOutlined } from '@ant-design/icons';
import Modals from '@/components/modals/Modals';
import { useKnowledgeStore } from '@/store/knowledge';
import { SvgIcon } from '@/components/icon';
import { AnnotationTypeItem, ClusterItemsType, FaqDataset } from '@/types/know/know';
import useModal from '@/hooks/use-modal/useModal';
import knowService from '@/api/services/knowService';
import { CustomDatePicker, Search, TextArea } from '@/components/eai-design';
import dayjs, { Dayjs } from 'dayjs';
import FaqListModal from '../components/faqListModal';
import DrawerView from '../components/DrawerView';

interface Props {
  open: boolean;
  onCancel: () => void;
  onOk: () => void;
  onOverlook?: () => void;
}

export default function UnanSwerableDisposeModal({ open, onCancel, onOk, onOverlook }: Props) {
  const [answer, setAnswer] = useState('');
  const [validDate, setValidDate] = useState<Dayjs | null>(null);
  const { unknownItem, setUnknownItem } = useKnowledgeStore();
  const [questions, setQuestions] = useState<ClusterItemsType[]>([]);
  const modal = useModal('editQuestion', 'faqOpen', 'test');
  const [showEdit, setShowEdit] = useState(true);
  const [titleValue, setTitleValue] = useState('');
  const [showAIAnswer, setShowAIAnswer] = useState(true);
  const [faqDataset, setFaqDataset] = useState<FaqDataset>({} as FaqDataset);
  const [aiLoading, setAiLoading] = useState(false);

  const [keyQuestionText, setKeyQuestionText] = useState('');
  const [keyQuestionQaId, setKeyQuestionQaId] = useState('');

  useEffect(() => {
    const list = unknownItem.clusterItems.map((item: ClusterItemsType) => {
      item.id = item.qaId_list[0];
      return item;
    });
    setQuestions(list);
    setShowEdit(true);
    setTitleValue(unknownItem.keyQuestionText);
    setFaqDataset({} as FaqDataset);
    setValidDate(null);
    setAnswer('');
    setShowAIAnswer(true);
  }, [unknownItem.clusterItems]);

  // 编辑问题
  const handleEdit = (id: string) => {
    setQuestions(questions.map((q) => (q.id === id ? { ...q, editable: true } : q)));
  };

  // 删除问题
  const handleDelete = async (qaId: string[]) => {
    try {
      await knowService.deleteUnknowQuestion({
        qaIdList: qaId,
        appId: unknownItem.appId,
      });
      setQuestions((prev) => prev.filter((q) => q.qaId_list[0] !== qaId[0]));
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 有效期设置
  const handleDateChange = (date: Dayjs | null) => {
    if (!date) {
      setValidDate(null);
      return;
    }
    const endOfDay = date.set('hour', 23).set('minute', 59).set('second', 59);
    setValidDate(endOfDay);
  };
  //AI润色
  const handerAICreate = async () => {
    if (aiLoading || answer.length < 10) {
      message.warning('请输入至少10个字符');
      return;
    }
    try {
      setAiLoading(true);
      let res;
      if (showAIAnswer) {
        //AI润色
        res = await knowService.aICreat({
          question: unknownItem.keyQuestionText,
          appId: unknownItem.appId,
          keyQuestionQaId: unknownItem.keyQuestionQaId,
        });
        setShowAIAnswer(false);
        setAnswer(res.aiembellish);
      } else {
        //撤回润色
        res = await knowService.AIback({
          question: unknownItem.keyQuestionText,
          keyQuestionQaId: unknownItem.keyQuestionQaId,
          appId: unknownItem.appId,
        });
        setAnswer(res);
        setShowAIAnswer(true);
      }
    } catch (error) {
      message.error('AI润色失败');
    } finally {
      setAiLoading(false);
    }
  };

  //写一个方法用来判断是否可以提交
  const isOk = () => {
    if (faqDataset.datasetId != undefined && faqDataset.datasetId != '' && answer.length != 0) {
      return true;
    }
    return false;
  };
  //提交
  const handleSubmit = async () => {
    if (faqDataset.datasetId == undefined || faqDataset.datasetId == '') {
      message.warning('请填写知识库');
      return;
    }
    if (answer.length == 0) {
      message.warning('请输入标准答案');
      return;
    }
    //收集参数
    const params = {
      appId: unknownItem.appId,
      keyQuestionQaId: unknownItem.keyQuestionQaId,
      question: titleValue,
      answer: answer,
      datasetId: faqDataset.datasetId,
      experiodTime: validDate ? validDate.format('YYYY-MM-DD HH:mm:ss') : '',
      qaIdList: questions.flatMap((item) => item.qaId_list),
    };
    try {
      await knowService.updateUnknowQuestionAnnotation(params as AnnotationTypeItem);
      onOk();
    } catch (error) {
      message.error(error as string);
    }
  };

  return (
    <>
      <Modals
        open={open}
        onCancel={onCancel}
        title="AI无法回答的问题"
        width={1050}
        modelContentClassName="!my-0 !py-3 !pr-0"
        footer={
          <div className="flex justify-end gap-2 border-t border-t-line-2 p-4">
            <div
              className={`ml-4 flex h-[32px] w-[68px] cursor-pointer items-center justify-center rounded-md border 
                   !border-@brand-color !text-@brand-color
              `}
              onClick={onOverlook}
            >
              忽略
            </div>
            <div
              className={`ml-4 flex h-[32px] w-[68px]  items-center justify-center rounded-md border text-white 
                   ${
                     isOk()
                       ? 'cursor-pointer !border-@brand-color !bg-@brand-color'
                       : '!border-@brand-disabled cursor-not-allowed !bg-@brand-color-disabled'
                   }
              `}
              style={
                isOk() ? { background: 'linear-gradient(90deg, #1B6DFA 0%, #00D0FE 181.25%)' } : {}
              }
              onClick={handleSubmit}
            >
              完成
            </div>
          </div>
        }
      >
        <div className="flex ">
          {/* 左侧问题列表 */}
          <div className="w-1/3 border-r border-r-line-2 pr-4">
            <div className="mb-2 flex items-center text-base font-bold text-@brand-color">
              {showEdit ? (
                <span className="mr-2">{unknownItem.keyQuestionText}</span>
              ) : (
                <div>
                  <Search
                    value={titleValue}
                    onChange={(e) => {
                      setTitleValue(e.target.value);
                    }}
                    placeholder="请输入问题名称"
                  />
                </div>
              )}
              {showEdit ? (
                <SvgIcon
                  size={20}
                  className="cursor-pointer"
                  icon="edit"
                  onClick={async () => {
                    setShowEdit(!showEdit);
                    setTitleValue(unknownItem.keyQuestionText);
                  }}
                />
              ) : (
                <div className="flex items-center gap-2">
                  <CheckOutlined
                    className="cursor-pointer"
                    onClick={async () => {
                      await knowService.updateUnknowQuestion({
                        keyQuestionQaId: unknownItem.keyQuestionQaId,
                        appId: unknownItem.appId,
                        title: titleValue,
                      });
                      message.success('修改成功');
                      setUnknownItem({
                        ...unknownItem,
                        keyQuestionText: titleValue,
                      });
                      setShowEdit(true);
                    }}
                  />
                  <CloseOutlined
                    className="cursor-pointer"
                    onClick={async () => {
                      setShowEdit(!showEdit);
                    }}
                  />
                </div>
              )}
            </div>
            <div className="mb-2 border-b border-line-1 pb-2 text-sm text-text-3">
              以下内容由系统自动聚类，请删除与本话题不符的问题，确保标准答案精准命中。
            </div>
            <div className="hide-scrollbar flex h-[320px] flex-col gap-1 overflow-y-auto text-sm text-text-5">
              {questions.map((item: ClusterItemsType, index: number) => (
                <div
                  key={index}
                  className={`flex cursor-pointer items-center  border-text-2 px-2 py-1 `}
                >
                  <>
                    <span className="flex-1 truncate">{item.query}</span>
                    {/* <div
                      onClick={(e) => {
                        e.stopPropagation();
                        handleEdit(item.qaId_list[0]);
                        setKeyQuestionText(item.query);
                        setKeyQuestionQaId(unknownItem.keyQuestionQaId);
                        modal.test.open();
                      }}
                      className="mx-2 text-text-3"
                    >
                      测试
                    </div> */}
                    <div
                      onClick={(e) => {
                        e.stopPropagation();
                        handleDelete(item.qaId_list);
                      }}
                      className=" flex items-center gap-1 text-text-3"
                    >
                      <SvgIcon size={16} icon="message-ic21" />
                      删除
                    </div>
                  </>
                </div>
              ))}
            </div>
          </div>
          {/* 右侧标准答案编辑 */}
          <div className="flex flex-1 flex-col pl-4">
            <div className="mb-2 flex h-[40px] items-center rounded-lg border border-geekblue-1 bg-geekblue-1 text-xs leading-[40px] text-text-5">
              <SvgIcon size={20} className="mx-2 cursor-pointer" icon="report-is-outline" />
              针对 AI
              无法回答的问题，补充文档或添加标准答案后，AI可能覆盖更多场景，显著提升回答覆盖率与用户体验。
            </div>
            <div className=" rounded-lg  bg-bg-3   p-4 text-text-3">
              <div className="flex items-center justify-between">
                <div>
                  <div className="mb-2 flex items-center">
                    <span className="text-base font-semibold text-text-5">添加标准答案</span>
                  </div>
                  <div className="mb-2 text-sm text-text-3">
                    输入标准答案，用户后续询问相关问题从标准答案形式回复用户
                  </div>
                </div>
                <div className="flex items-center">
                  <div
                    className={`
                     flex items-center rounded-md border border-line-2 px-2 py-1 text-sm font-semibold
                    ${aiLoading || answer.length < 10 ? 'cursor-not-allowed ' : 'cursor-pointer '}
                    `}
                    style={
                      answer.length < 10
                        ? {
                            background:
                              'linear-gradient(90deg, rgba(146, 83, 244, 0.10) -11.61%, rgba(39, 119, 255, 0.10) 52.92%, rgba(0, 208, 254, 0.10) 116.22%), #FFF',
                            opacity: 0.5,
                            color: 'var(--disabled, #BADDFF)',
                          }
                        : {
                            background:
                              'linear-gradient(90deg, rgba(146, 83, 244, 0.10) -11.61%, rgba(39, 119, 255, 0.10) 52.92%, rgba(0, 208, 254, 0.10) 116.22%), #FFF',
                            opacity: 1,
                            color: '#1D2129',
                          }
                    }
                    onClick={() => {
                      if (!aiLoading && answer.length >= 10) handerAICreate();
                    }}
                  >
                    {aiLoading ? (
                      <LoadingOutlined spin />
                    ) : (
                      <SvgIcon size={16} icon="report-is-runse" />
                    )}
                    <span
                      style={
                        answer.length < 10
                          ? undefined
                          : {
                              backgroundImage:
                                'linear-gradient(90deg, rgba(146, 83, 244, 1) -11.61%, rgba(39, 119, 255, 1) 52.92%, rgba(0, 208, 254, 1) 116.22%)',
                              WebkitBackgroundClip: 'text',
                              backgroundClip: 'text',
                              WebkitTextFillColor: 'transparent',
                              color: '透明',
                            }
                      }
                    >
                      {showAIAnswer ? 'AI润色' : '撤回润色'}
                    </span>
                  </div>
                  {/* <Button
                    type="default"
                    className="ml-2 !bg-[#F7F8F8]"
                    onClick={() => {
                      modal.test.open();
                      setKeyQuestionText(unknownItem.keyQuestionText);
                      setKeyQuestionQaId(unknownItem.keyQuestionQaId);
                    }}
                  >
                    测试
                  </Button> */}
                </div>
              </div>
              <TextArea
                placeholder="请输入标准答案"
                autoSize={{ minRows: 15, maxRows: 15 }}
                value={answer}
                onChange={(e) => setAnswer(e.target.value)}
                className="border border-text-2 "
              />

              <div className="mt-2 flex items-center gap-2 text-sm text-text-4">
                存放至
                <div
                  className="flex w-[200px]  cursor-pointer items-center justify-between rounded-lg border border-line-2 bg-white px-2 py-1  text-text-4"
                  onClick={() => {
                    modal.faqOpen.open();
                  }}
                >
                  <span>
                    <span className={`${faqDataset.datasetId ? 'text-text-4' : 'text-text-2'}`}>
                      {faqDataset.datasetId ? faqDataset?.datasetName : '请选择存放位置'}
                    </span>
                  </span>
                  <RightOutlined />
                </div>
                <span className="  ">
                  答案有效期：
                  {/* <span className="mr-2">{validDate ? validDate.format('YYYY-MM-DD') : '无'}</span> */}
                  <CustomDatePicker
                    placeholder="无有效期"
                    value={validDate as Dayjs}
                    onChange={handleDateChange}
                    disabledDate={(current) => {
                      return current && current < dayjs().startOf('day');
                    }}
                  />
                </span>
              </div>
            </div>
          </div>
        </div>
      </Modals>
      <FaqListModal
        open={modal.faqOpen.isOpen}
        onOk={(item) => {
          setFaqDataset(item);
          modal.faqOpen.close();
        }}
        onCancel={() => modal.faqOpen.close()}
        appId={unknownItem.appId}
      />
      <DrawerView
        open={modal.test.isOpen}
        onClose={() => {
          modal.test.close();
        }}
        keyQuestionText={keyQuestionText}
        keyQuestionQaId={keyQuestionQaId}
      />
      {/* <EditQuestionModal
        open={modal.editQuestion.isOpen}
        value={unknownItem.keyQuestionText}
        onOk={(value) => {}}
        onCancel={() => modal.editQuestion.close()}
      /> */}
    </>
  );
}
